x$.ready(function () {
	
	var chuoiHienThi = '';
	var mangToken = [];
	var args = [];
	var argsArrayIndex = 0;
	var memory = "";
	var mode = '0';
	var currentMode = '11';
	var justPressedNumKey = false;
	var lastMode = '0';
	
	// Display decleration
	var displayInput = x$('.displayInput');
	var displayResult = x$('.displayResult');
	var displaySign = x$('.displaySign');
	var displayArg = x$('.displayArg');
	
	var variableName11 = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2'];
	var variableName12 = ['a1', 'b1', 'c1', 'd1', 'a2', 'b2', 'c2', 'd2', 'a3', 'b3', 'c3', 'd3'];
	var variableName21 = ['a', 'b', 'c'];
	var variableName22 = ['a', 'b', 'c', 'd'];
	
	var inMode = false;
	
	var reset = function()
	{
		chuoiHienThi = '';
		mangToken = [];
		
		displayInput.setStyle('font-family', 'Tahoma');
		displayInput.setStyle('font-size', '30');
		
		displayResult.setStyle('font-family', 'ds-digitalitalic');
		displayResult.setStyle('font-size', '38px');
		
		displayInput.html(chuoiHienThi);
		displayResult.html('0');
		displayArg.html('');
		
		args = [];
		argsArrayIndex = 0;
		mode = 0;
		currentMode = '11';
		justPressedNumKey = false;
		inMode = false;
	};	
	
	var displayMode = function(dis, val)
	{	
		dis.setStyle('font-family', 'bpdotssquaresregular');
		dis.setStyle('font-size', '30px');
		// dis.css({font-family: 'bpdotssquaresregular', font-size: '30px'})
		dis.html(val + '');
		// dis.attr('style', style);
		// dis.setStyle('font-size', font_size + '');
	}
	
	var display = function(dis, val)
	{
		val += '';
		if (dis == displayInput)
		{
			dis.html(('' + val).substring(val.length - 18, val.length));			
		}
		else 
		{
			var posOfMinus = 0;
			if((val-0) < 0) posOfMinus = 1;
			
			var posOfPoint = val.indexOf('.');
			if(posOfPoint < 0) posOfPoint = val.length;
		
			var decimal = val.substring(posOfMinus, posOfPoint-posOfMinus+(val-0<0?1:0));
			var real = val.substring(posOfPoint+1, val.length);
			
			var d = '';
			if (decimal.length <= 3)
			{
				d += decimal;
			}
			else 
			{
				var mod = decimal.length % 3;
				if (mod > 0)
				{
					d += decimal.substring(0, mod) + "'";
				}
				for (var i = mod; i < decimal.length; i += 3)
				{
					d += decimal.substring(i, i + 3) + "'";
				}
				d = d.substring(0, d.length - 1);
			}
			
			if (val - 0 < 0)
			{
				d = '-' + d;
			}
			
			if (!(posOfPoint == val.length))
			{
				d += '.' + real;
			}
			dis.html(('' + d).substring(0, 16));
		}		
	};
	
	// Initialization 
	reset();
	
	window.btnNum = function(num)
	{
		if (num >= 0 && num <= 9)
		{
			if (inMode == true)
			{
				if (num == 1 || num == 2)
				{
					currentMode = '' + mode + num;
					console.log(currentMode);
					args = [];
					inMode = false;
					executeMode();
					mode = 0;
				}
			}
			else
			{
				chuoiHienThi += num;
				display(displayInput, chuoiHienThi);
				if (justPressedNumKey)
				{
					mangToken[mangToken.length - 1] += num + '';
				}
				else
				{
					mangToken[mangToken.length] = num;
					justPressedNumKey = true;
				}
			}
		}
		
		else if (num == '+' || num == '-' || num == 'x' || num == '/')
		{
			if (inMode == false)
			{
				chuoiHienThi += (num == '/' ? String.fromCharCode(247) : num);
				display(displayInput, chuoiHienThi);
				mangToken[mangToken.length] = ' ' + num + ' ';
				justPressedNumKey = false;
			}
		}
		else if (num == '.') 
		{		
			if (inMode == false)
			{
				if (justPressedNumKey)
				{
					mangToken[mangToken.length - 1] += '.';
					chuoiHienThi += '.';
				}
				else
				{
					chuoiHienThi += '0.';
					mangToken[mangToken.length] = '0.';
					justPressedNumKey = true;
				}
				display(displayInput, chuoiHienThi);
			}
		}
		
		// else if (num == 'inv')
		// {
			// chuoiHienThi += ' -';
			// display(displayInput, chuoiHienThi);
			// mangToken[mangToken.length] = ' -';
			// justPressedNumKey = true;
		// }
		
		else if (num == 'backspace')
		{
			if (inMode == false)
			{
				console.log('before: [' + mangToken + ']');
				if (mangToken.length != 0)
				{
					// Cai nay de sau
					if (isNaN(mangToken[mangToken.length - 1] - 0))
					{
						// delete mangToken[mangToken.length - 1];
						mangToken.length--;
					}
					else
					{
						var s = mangToken[mangToken.length - 1];
						s = ('' + s).substring(0, s.length - 1);
						if (s == '')
						{
							mangToken.length--;
						}
						else
						{
							mangToken[mangToken.length - 1] = s;
						}
						
					}
				}
				if (isNaN(mangToken[mangToken.length - 1] - 0))
				{
					justPressedNumKey = false;
				}
				else
				{
					justPressedNumKey = true;
				}
				chuoiHienThi = mangToken2ChuoiHienThi();
				display(displayInput, chuoiHienThi);
			}
		}
		else if (num == 'ac')
		{
			reset();
		}
		else if (num == 'mr')
		{
			if (inMode == false)
			{
				chuoiHienThi += memory;
				mangToken[mangToken.length] = memory;
				display(displayInput, chuoiHienThi);
			}
		}
		else if (num == 'mw')
		{
			try
			{
				memory = evaluate(mangToken);
				display(displayResult, evaluate(mangToken));
			}
			catch(err)
			{
				display(displayInput, err.message);
			}
			finally
			{
				mangToken = [];
				chuoiHienThi = '';				
			}
		}
		else if (num == 'sin' || num == 'cos' || num == 'tan' || num == 'cot' || num == 'ln'  || num == '^' || num == 'v' || 			num == 'log')
		{
			if (inMode ==false)
			{
				chuoiHienThi += (num == 'v' ? '\u221A' : num) + '(';
				display(displayInput, chuoiHienThi);
				mangToken[mangToken.length] = ' ' + num + ' ( ';
				justPressedNumKey = false;
			}
		}
		else if (num == 'sqr')
		{
			if (inMode == false)
			{
				chuoiHienThi += '^2';
				display(displayInput, chuoiHienThi);
				mangToken[mangToken.length] = ' ^ ( 2 ) ' ;
				justPressedNumKey = false;
			}
		}
		else if (num == 'sqrt')
		{
			if (inMode == false)
			{
				chuoiHienThi += '\u221A' + '(';
				display(displayInput, chuoiHienThi);
				mangToken[mangToken.length] = '2 v ( ';
				justPressedNumKey = false;
			}
		}
		else if (num == '(' || num == ')')
		{
			if (inMode == false)
			{
				chuoiHienThi += num;
				display(displayInput, chuoiHienThi);
				mangToken[mangToken.length] = ' ' + num + ' ';
				justPressedNumKey = false;
			}
		}
		else if (num == '=')
		{	
			if (currentMode == '11')
			{
				try
				{
					display(displayResult, evaluate(mangToken));
				}
				catch(err)
				{
					display(displayInput, err.message);
				}
				finally
				{
					mangToken = [];
					chuoiHienThi = '';				
				}
			}
			else
			{
				if (currentMode == '21')
				{
					if (argsArrayIndex < 5)
					{
						display(displayResult, args[argsArrayIndex + 1] == undefined ? '0' : args[argsArrayIndex + 1]);
						var temp;
						if (mangToken.length != 0)
						{
							try
							{
								temp = evaluate(mangToken);
							}
							catch(err)
							{
								display(displayInput, err);
							}		
						}
						else
						{
							if (args[argsArrayIndex] == undefined)
							{
								temp = 0;
							}
							else
							{
								temp = args[argsArrayIndex];
							}
						}
										
						args[argsArrayIndex] = temp;
						display(displayArg, variableName11[argsArrayIndex + 1] + '=');					
						chuoiHienThi = '';
						mangToken = [];
						display(displayInput, chuoiHienThi);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 5)
					{
						display(displayResult, args[argsArrayIndex + 1] == undefined ? '0' : args[argsArrayIndex + 1]);
						var temp;
						if (mangToken.length != 0)
						{
							try
							{
								temp = evaluate(mangToken);
							}
							catch(err)
							{
								display(displayInput, err);
							}		
						}
						else
						{
							if (args[argsArrayIndex] == undefined)
							{
								temp = 0;
							}
							else
							{
								temp = args[argsArrayIndex];
							}
						}						
						args[argsArrayIndex] = temp;
						var clone = args.slice(0);
						console.log('clone ' + clone);
						result = gauss_jordan(clone, 2);
						if (typeof(result) == 'string')
						{
							display(displayArg, '');
							display(displayInput, result);
							argsArrayIndex++;
						}
						else 
						{
							display(displayInput, '');
							display(displayArg, 'x=');
							display(displayResult, result[0]);
						}
						argsArrayIndex++;					
					}
					else if (argsArrayIndex == 6)
					{
						display(displayInput, '');
						display(displayArg, 'y=');
						display(displayResult, result[1]);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 7)
					{
						argsArrayIndex = 0;
						executeMode();
					}		
				}
				else if (currentMode == '22')
				{
					if (argsArrayIndex < 11)
					{	
						display(displayResult, args[argsArrayIndex + 1] == undefined ? '0' : args[argsArrayIndex + 1]);
						var temp;
						if (mangToken.length != 0)
						{
							try
							{
								temp = evaluate(mangToken);
							}
							catch(err)
							{
								display(displayInput, err);
							}		
						}
						else
						{
							if (args[argsArrayIndex] == undefined)
							{
								temp = 0;
							}
							else
							{
								temp = args[argsArrayIndex];
							}
						}					
						args[argsArrayIndex] = temp;
						display(displayArg, variableName12[argsArrayIndex + 1] + '=');					
						chuoiHienThi = '';
						mangToken = [];
						display(displayInput, chuoiHienThi);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 11)
					{
						display(displayResult, args[argsArrayIndex + 1] == undefined ? '0' : args[argsArrayIndex + 1]);
						var temp;
						if (mangToken.length != 0)
						{
							try
							{
								temp = evaluate(mangToken);
							}
							catch(err)
							{
								display(displayInput, err);
							}		
						}
						else
						{
							if (args[argsArrayIndex] == undefined)
							{
								temp = 0;
							}
							else
							{
								temp = args[argsArrayIndex];
							}
						}				
						args[argsArrayIndex] = temp;
						var clone = args.slice(0);
						result = gauss_jordan(clone, 3);
						if (typeof(result) == 'string')
						{
							display(displayResult, 0);
							display(displayArg, '');
							display(displayInput, result);
							argsArrayIndex+=2;
						}
						else 
						{
							display(displayInput, '');
							display(displayArg, 'x=');
							display(displayResult, result[0]);
						}
						argsArrayIndex++;					
					}
					else if (argsArrayIndex == 12)
					{
						display(displayInput, '');
						display(displayArg, 'y=');
						display(displayResult, result[1]);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 13)
					{
						display(displayInput, '');
						display(displayArg, 'z=');
						display(displayResult, result[2]);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 14)
					{
						argsArrayIndex = 0;
						executeMode();
					}					
				}
				else if (currentMode == '31')
				{
					if (argsArrayIndex < 2)
					{					
						display(displayResult, args[argsArrayIndex + 1] == undefined ? '0' : args[argsArrayIndex + 1]);
						var temp;
						if (mangToken.length != 0)
						{
							try
							{
								temp = evaluate(mangToken);
							}
							catch(err)
							{
								display(displayInput, err);
							}		
						}
						else
						{
							if (args[argsArrayIndex] == undefined)
							{
								temp = 0;
							}
							else
							{
								temp = args[argsArrayIndex];
							}
						}				
						args[argsArrayIndex] = temp;
						display(displayArg, variableName21[argsArrayIndex + 1] + '=');					
						chuoiHienThi = '';
						mangToken = [];
						display(displayInput, chuoiHienThi);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 2)
					{
						display(displayResult, args[argsArrayIndex + 1] == undefined ? '0' : args[argsArrayIndex + 1]);
						var temp;
						if (mangToken.length != 0)
						{
							try
							{
								temp = evaluate(mangToken);
							}
							catch(err)
							{
								display(displayInput, err);
							}		
						}
						else
						{
							if (args[argsArrayIndex] == undefined)
							{
								temp = 0;
							}
							else
							{
								temp = args[argsArrayIndex];
							}
						}					
						args[argsArrayIndex] = temp;
						result = giaiPtBac2(args);
						if (typeof(result) == 'string')
						{
							display(displayArg, '');
							display(displayInput, result);
							argsArrayIndex++;
						}
						else 
						{
							display(displayInput, '');
							if (result.length == 1)
							{
								display(displayArg, 'x=');
								display(displayResult, result[0]);
								argsArrayIndex++;
							}
							else
							{
								display(displayArg, 'x1=');
								display(displayResult, result[0]);
							}
						}
						argsArrayIndex++;					
					}
					else if (argsArrayIndex == 3)
					{
						display(displayInput, '');
						display(displayArg, 'x2=');
						display(displayResult, result[1]);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 4)
					{
						argsArrayIndex = 0;
						executeMode();
					}
				}
				else if (currentMode == '32')
				{
					if (argsArrayIndex < 3)
					{					
						display(displayResult, args[argsArrayIndex + 1] == undefined ? '0' : args[argsArrayIndex + 1]);
						var temp;
						if (mangToken.length != 0)
						{
							try
							{
								temp = evaluate(mangToken);
							}
							catch(err)
							{
								display(displayInput, err);
							}		
						}
						else
						{
							if (args[argsArrayIndex] == undefined)
							{
								temp = 0;
							}
							else
							{
								temp = args[argsArrayIndex];
							}
						}					
						args[argsArrayIndex] = temp;
						display(displayArg, variableName22[argsArrayIndex + 1] + '=');					
						chuoiHienThi = '';
						mangToken = [];
						display(displayInput, chuoiHienThi);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 3)
					{
						display(displayResult, args[argsArrayIndex + 1] == undefined ? '0' : args[argsArrayIndex + 1]);
						var temp;
						if (mangToken.length != 0)
						{
							try
							{
								temp = evaluate(mangToken);
							}
							catch(err)
							{
								display(displayInput, err);
							}		
						}
						else
						{
							if (args[argsArrayIndex] == undefined)
							{
								temp = 0;
							}
							else
							{
								temp = args[argsArrayIndex];
							}
						}		
						args[argsArrayIndex] = temp;
						result = giaiPtBac3(args);
						if (typeof(result) == 'string')
						{
							display(displayResult, '0');
							display(displayArg, '');
							display(displayInput, result);
							argsArrayIndex += 2;
						}
						else 
						{
							display(displayInput, '');
							if (result.length == 1)
							{
								display(displayArg, 'x=');
								display(displayResult, result[0]);
								argsArrayIndex += 2;
							}
							else
							{
								display(displayArg, 'x1=');
								display(displayResult, result[0]);
							}
						}
						argsArrayIndex++;					
					}
					else if (argsArrayIndex == 4)
					{
						if (result.length == 2)
						{
							argsArrayIndex++;
						}
						display(displayInput, '');
						display(displayArg, 'x2=');
						display(displayResult, result[1]);
						argsArrayIndex++;
					}
					else if (argsArrayIndex == 5)
					{
						display(displayInput, '');
						display(displayArg, 'x3=');
						display(displayResult, result[1]);
						argsArrayIndex++;						
					}
					else if (argsArrayIndex == 6)
					{
						argsArrayIndex = 0;
						executeMode();
					}
				}
			}
			justPressedNumKey = false;
		}
		else if (num == 'mode')
		{	
			display(displayArg, '');
			// mode la trang hien tai trong mode.
			// displayInput.setStyle('font-family', 'bpdotssquaresregular');
			mode++;
			inMode = true;
			if (mode == 1)
			{
				lastMode = currentMode;
				displayMode(displayInput, '1: Normal mode&nbsp;&nbsp;');
				displayMode(displayResult, '');
			}
			else if (mode == 2)
			{
				displayMode(displayInput, '1: He PT 2 an&nbsp;&nbsp;&nbsp;');
				displayMode(displayResult, '2: He PT 3 an&nbsp;&nbsp;&nbsp;');
			}
			else if (mode == 3)
			{
				displayMode(displayInput, '1: PT 1 an bac 2');
				displayMode(displayResult, '2: PT 1 an bac 3');
			}
			else if (mode == 4)
			{
				mode = 0;
				currentMode = lastMode;
				if (currentMode == '11')
				{
					inMode = false;
				}
				executeMode();
			}
		}
	};
	
	/**
	@param: leftParam is not displaying in the sreen.
	@param: rightParam is what displaying in the screen
	return a string.
	*/
	
	var executeMode = function()
	{
		displayInput.setStyle('font-family', 'Tahoma');
		displayInput.setStyle('font-size', '30');
		
		displayResult.setStyle('font-family', 'ds-digitalitalic');
		displayResult.setStyle('font-size', '38px');
		
		chuoiHienThi = '';
		mangToken = [];
		display(displayInput, chuoiHienThi);
		display(displayResult, '0');
		argsArrayIndex = 0;
		
		
		if (currentMode == '21' || currentMode == '22')
		{
			// Giai he PT
			display(displayArg, 'a1=');
			display(displayResult, args[0] == undefined ? '0' : args[0]);
			
		}
		else if (currentMode == '31' || currentMode == '32')
		{
			// Giai PT
			display(displayArg, 'a=');
			display(displayResult, args[0] == undefined ? '0' : args[0]);
		}
	}
	
	var scale = function()
	{
		var oW = 320, oH = 508;
		var W = window.innerWidth;
		var H = window.innerHeight;
		
		var scaleX = W / oW;
		var scaleY = H / oH;
		
		for (var i=1; i<= 35; i++)
		{
			var e = x$('#b'+i);
			
			var v = function(n, s)
			{
				var m = 1;
				if(typeof s != 'undefined')
				{
					m = s;
				}
				var t = '' + e.getStyle(n);
				t = t.replace('px', '');
				return ((t-0)*m)+'px';
			};
			
			e.css({
				width  : v('width', scaleX),
				height : v('height', scaleY),
				top    : v('top', scaleY),
				left   : v('left', scaleX)
			});
		}
		
	};
	
	scale();
	

	var mangToken2ChuoiHienThi = function()
	{
		var temp = '';
		for (var i = 0; i < mangToken.length; i++)
		{
			var s = ('' + mangToken[i]).trim();
			s = s.removeAllSpace();
			if (s == '/')
			{
				s = String.fromCharCode(247);
			}
			else if (s == '2v(')
			{
				s = '\u221A' + '(';
			}
			else if (s == '^(2)')
			{
				s = '^2';
			}
			temp += s;
		}
		return temp;
	}
	
	String.prototype.trim = function() 
	{
		return this.replace(/^\s+|\s+$/g, "");
	};
	String.prototype.removeAllSpace = function()
	{
		return this.replace(/\s+/g, '');
	}
});
